package com.zhkj.crawl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhkj.crawl.bean.FetchPhpParams;
import com.zhkj.crawl.entity.ListingRecord;
import com.zhkj.crawl.entity.ResultAmz;
import com.zhkj.crawl.entity.ResultAmzForPush;
import com.zhkj.crawl.utils.TimeDistance;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PhpService {
    private static final String FETCH_LINK = "http://dms.izehui.com/server/api/v1/dms/fba/get-out-sku-list?part_sum=%s&part_number=%s";
    private static final String PUSH_LINK = "http://dms.izehui.com/server/api/v1/dms/fba/input-sku-rank-data";

    @Autowired
    private ListingService listingService;

    public int syncPhpListing(FetchPhpParams params){
        int part = params.getSize();
        int result = 0;
        for (int i = 0; i < part; i++) {
            String url = String.format(FETCH_LINK, part, i);
            try {
                TimeDistance td = new TimeDistance();
                String text = fetchData(url, 0);
                td.dot();
                JSONObject data = JSON.parseObject(text);
                JSONArray arr = data.getJSONArray("data");
                List<ListingRecord> records = arr.toJavaList(ListingRecord.class);

                List<ListingRecord> collect = records.stream()
                        .filter(s -> StringUtils.isNoneBlank(s.getAsin(), s.getSite()))
                        .collect(Collectors.toList());
                td.dot();
                long current = listingService.batchSave(collect);
                td.dot();
                result += current;
                log.info("fetch php listing. page {} size {} insert {}, 耗时（fetch {}，package {}, db {}）",
                        i, collect.size(), current, td.pop(), td.pop(), td.pop());
            }catch (Exception e){
                log.error(String.format("抓取php数据错误（%s）", url), e);
            }
        }

        return result;
    }

    public static String fetchData(String url, Integer deep){
        ++deep;
        try {
            return Jsoup.connect(url).ignoreContentType(true).get().body().text();
        }catch (IOException e){
            log.info("拉取php数据超时, retry{} {}", deep, url);
            if(deep < 5){
                try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException ignore) { }
                return fetchData(url, deep);
            }
        }
        return null;
    }

    public void pushResult(List<ResultAmz> doneList) {
        log.info("开始推送结果 {}条 => php", doneList.size());
        int size = 500;

        List<ResultAmzForPush> data = doneList.stream()
                .filter(s -> StringUtils.isNotBlank(s.getRankStr()))
                .map(s -> {
                    ResultAmzForPush res = BeanUtil.copyProperties(s, ResultAmzForPush.class);
                    res.setGrab_time(s.getUpdateTime().getTime());
                    res.setRank_str(s.getRankStr());
                    res.setReview(s.getRating());
                    res.setStar(s.getStar());
                    return res;
                }).collect(Collectors.toList());

        List<List<ResultAmzForPush>> split = CollUtil.split(data, size);

//        String url = "http://10.10.30.182:3000/mock/297/api/v1/dms/fba/input-sku-rank-data";
        for (List<ResultAmzForPush> subList : split) {
            JSONObject param = new JSONObject();
            param.put("sku_array", subList);
            String body = HttpRequest.post(PUSH_LINK).body(param.toString()).execute().body();
            log.info("推送{}条结果到php - {}", subList.size(), body);
        }
    }
}
